package com.meisen.springboot.configuration;

import com.meisen.springboot.interceptor.RequestInterceptor;
import com.meisen.springboot.interceptor.URLInterceptor;
import com.meisen.springboot.service.IpBlackListService;
import com.meisen.springboot.service.IpWhiteListService;
import com.meisen.springboot.util.IpAddressUtils;
import com.springboot.meisen.core.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class WebAppConfigurer extends WebMvcConfigurationSupport {

    private final IpAddressUtils ipAddressUtils;
    private final IpBlackListService ipBlackListService;
    private final IpWhiteListService ipWhiteListService;

    @Autowired
    public WebAppConfigurer(IpAddressUtils ipAddressUtils, IpBlackListService ipBlackListService, IpWhiteListService ipWhiteListService) {
        this.ipAddressUtils = ipAddressUtils;
        this.ipBlackListService = ipBlackListService;
        this.ipWhiteListService = ipWhiteListService;
    }

    @Bean   //把我们的拦截器注入为bean
    public HandlerInterceptor getMyInterceptor(){
        return new URLInterceptor(ipBlackListService, ipAddressUtils, ipWhiteListService);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins(Constants.ORIGIN)
                .allowedMethods("*").allowedHeaders("*")
                .allowCredentials(true)
                .exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L);
    }

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/api/image/**").addResourceLocations("file:/Users/meisen/IdeaProjects/static/");
        super.addResourceHandlers(registry);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 多个拦截器组成一个拦截器链
        // addPathPatterns 用于添加拦截规则, 这里拦截 /api 后面的全部链接
        // excludePathPatterns 用户排除拦截
        registry.addInterceptor(getMyInterceptor())
                .addPathPatterns("/api/**");
        registry.addInterceptor(new RequestInterceptor())
                .addPathPatterns("/api/**");
        super.addInterceptors(registry);
    }
}
